<?php

namespace App\Logic;

use App\Model\ImGroupMessage;
use App\Model\Live;
use App\Model\LiveColumn;
use App\Model\LiveSessionGift;
use App\Model\Play;
use App\Model\User;
use App\Model\UserModelAnchor;
use App\Service\LiveService;
use App\Utils\Enum\UserEnum;
use App\Utils\Log;
use Exception;

class AdminLiveLogic
{
    /**
     * 直播列表
     * @param $input
     * @return array
     */
    public static function listLive($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = Live::query()->when(!empty($input['query']['match_id']), function ($query) use ($input) {
            $query->where('match_id', $input['query']['match_id']);
        })->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            $query->where('room_name', 'like', '%' . $input['query']['keyword'] . '%');
        })->when(isset($input['query']['status']) && intval($input['query']['status']), function ($query) use ($input) {
            $query->where('status', intval($input['query']['status']));
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user', 'anchor'])->limit($pageSize)->offset($offset)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 直播详情
     * @param $roomId
     * @return array
     */
    public static function detailLive($roomId): array
    {
        return Live::query()->where('room_id', $roomId)->with(['anchor', 'user'])->first()->toArray();
    }

    /**
     * 修改直播间信息
     * @throws Exception
     */
    public static function editLive($roomId, $input): true
    {
        $roomInfo = Live::query()->where('room_id', $roomId)->first();
        if (!$roomInfo) {
            throw new Exception('直播间不存在');
        }
        $data = $anchorUpdate = [];
        if (isset($input['roomName'])) {
            $data['room_name'] = $input['roomName'];
        }
        if (isset($input['roomBanner'])) {
            $data['room_banner'] = $input['roomBanner'];
        }
        if (isset($input['matchId'])) {
            $matchInfo = Play::query()->where('match_id', $input['matchId'])->first();
            if (!$matchInfo) {
                throw new Exception('比赛不存在');
            }
            $data['match_id'] = $matchInfo['match_id'];
            $data['match_status'] = $matchInfo['match_status'];
            $data['match_time'] = $matchInfo['match_time'];
        }
        if (isset($input['columnId'])) {
            $data['column_id'] = $anchorUpdate['column_id'] = (int)$input['columnId'];
        }
        if (isset($input['assistantUserId'])) {
            $assistantUser = User::query()->where(['id' => $input['assistantUserId'], 'role_id' => UserEnum::USER_TYPE_ASSIST])->first();
            if (!$assistantUser) {
                throw new Exception('对应助理不存在');
            }
            $data['assistant_userid'] = $anchorUpdate['assistant_userid'] = (int)$input['assistantUserId'];
        }
        if (isset($input['announcement'])) {
            $data['announcement'] = $input['announcement'];
        }
        if (isset($input['introduce'])) {
            $data['introduce'] = $input['introduce'];
        }
        if (isset($input['roomCover'])) {
            $data['room_cover'] = $input['roomCover'];
        }
        if (isset($input['isVirtual'])) {
            $data['is_virtual'] = $input['isVirtual'];
        }
        if (isset($input['visitHistory'])) {
            $data['visit_history'] = (int)$input['visitHistory'];
        }
        if (!empty($data)) {
            try {
                Live::query()->where('id', $roomInfo['id'])->update($data);
                if (!empty($anchorUpdate)) {
                    UserModelAnchor::query()->where('room_id', $roomId)->update($anchorUpdate);
                }
            } catch (Exception $e) {
                Log::error(sprintf('修改直播间信息失败:%s', $e->getMessage()));
                throw new Exception('修改失败');
            }
        }
        return true;
    }

    /**
     * 断流
     * @param $roomId
     * @return true
     */
    public static function cutOffStream($roomId): true
    {
        LiveService::dropLiveStream($roomId);
        return true;
    }

    /**
     * 直播礼物列表
     * @param $input
     * @return array
     */
    public static function giftRecords($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = LiveSessionGift::query()->when(!empty($input['query']['roomId']), function ($query) use ($input) {
            $query->where('room_id', $input['query']['roomId']);
        })->when(!empty($input['query']['keyword']), function ($query) use ($input) {
            $query->where('userid', AdminUserLogic::findUserId($input['query']['keyword']));
        })->when(!empty($input['query']['date']), function ($query) use ($input) {
            $query->where('idx_date', date('Ymd', strtotime($input['query']['date'])));
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user'])->limit($pageSize)->offset($offset)->orderBy('id', 'desc')->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 聊天记录
     * @param $input
     * @return array
     */
    public static function chatRecords($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $query = ImGroupMessage::query()->when(!empty($input['query']['groupId']), function ($query) use ($input) {
            $query->where('group_id', $input['query']['groupId']);
        });
        $total = $query->count();
        if ($total) {
            $records = $query->with(['user'])->limit($pageSize)->offset($offset)->orderBy('id', 'desc')->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }

    /**
     * 直播分类列表
     * @param $input
     * @return array
     */
    public static function listColumn($input): array
    {
        [$pageNum, $pageSize, $offset] = parsePageParams($input);
        $total = LiveColumn::query()->count();
        if ($total) {
            $records = LiveColumn::query()->orderBy('listorder', 'asc')->orderBy('id', 'asc')->limit($pageSize)->offset($offset)->get()->toArray();
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? []
        ];
    }


    /**
     * 添加直播分类
     * @throws Exception
     */
    public static function addColumn($input): array
    {
        $isExists = LiveColumn::query()->when('title', $input['title'])->exists();
        if ($isExists) {
            throw new Exception('该分类名称已存在');
        }
        $ret = LiveColumn::create([
            'title' => $input['title'],
            'image' => $input['image'],
            'sport_id' => $input['sportId'] ?? 0,
            'listorder' => $input['listorder'],
            'enable' => $input['enable'],
            'add_time' => time()
        ]);
        if (!$ret) {
            throw new Exception('添加失败');
        }
        return $ret->toArray();
    }

    /**
     * 修改直播分类
     * @param $id
     * @param $input
     * @return true
     * @throws Exception
     */
    public static function editColumn($id, $input): true
    {
        $column = LiveColumn::query()->where('id', $id)->first();
        if (!$column) {
            throw new Exception('该分类不存在');
        }
        if (LiveColumn::query()->where('id', '<>', $id)->where('title', $input['title'])->exists()) {
            throw new Exception('该分类名称已被使用');
        }
        try {
            LiveColumn::query()->where('id', $id)->update([
                'title' => $input['title'],
                'image' => $input['image'] ?? $column['image'],
                'sport_id' => $input['sportId'] ?? $column['sport_id'],
                'listorder' => $input['listorder'],
                'enable' => $input['enable'] ?? 0,
            ]);
        } catch (Exception $e) {
            throw new Exception('修改失败');
        }
        return true;
    }

    /**
     * 删除直播分类
     * @param $id
     * @return true
     * @throws Exception
     */
    public static function delColumn($id): true
    {
        if (LiveColumn::query()->where('id', $id)->exists()) {
            if (Live::query()->where('column_id', $id)->exists()) {
                throw new Exception('该栏目下有直播间，不可删除');
            }
            LiveColumn::query()->where('id', $id)->delete();
        }
        return true;
    }

    /**
     * 快速修改栏目参数
     * @param $catId
     * @param $field
     * @param $value
     * @return true
     * @throws Exception
     */
    public static function updateColumnField($catId, $field, $value): true
    {
        if (!in_array($field, ['listorder'])) {
            throw new Exception('不支持修改该值');
        }
        LiveColumn::query()->where('id', $catId)->update([$field => $value]);
        return true;
    }
}